<template>
  <a-card :bordered="false">
    <a-row :gutter="24">
      <a-col :md="6" :sm="24">
        <a-card hoverable style="height:600px;overflow-y:auto">
          <a-button type="primary" class="actionButton" @click="savePer">保存权限</a-button>
          <a-spin :spinning="loadingPer">
            <a-tree checkable :showLine="true" @expand="onExpand" :expandedKeys="expandedKeys"
              :autoExpandParent="autoExpandParent" v-model="checkedKeys" @select="onSelect"
              :selectedKeys="selectedMenuKeys" :treeData="treeData" :replaceFields="replaceFields" @check="onCheck" />
          </a-spin>
        </a-card>
      </a-col>
      <a-col :md="18" :sm="24">
        <div class="table-page-search-wrapper" style="margin-bottom:16px">
          <a-row style="margin-bottom:16px">
            <a-col :md="8" :sm="24">
              <a-input-search @search="search" enterButton="查询" />
            </a-col>
          </a-row>
          <a-row>
            <a-button type="primary" class="actionButton" @click="add">添加</a-button>
            <a-popconfirm v-if="isAdmin()" title="确定删除?" okText="确定" cancelText="取消" @confirm="del">
              <a-button type="primary" class="actionButton">删除</a-button>
            </a-popconfirm>
          </a-row>
        </div>
        <a-spin :spinning="spinning" tip="获取数据中...">
          <div class="spin-content">
            <a-table size="small" bordered :rowKey="record => record.ID" :columns="columns" :dataSource="data"
              :customRow="setRow" :rowClassName="setRowClassName" :pagination="pagination"
              :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
              <span slot="action" slot-scope="text, record">
                <template>
                  <a-tooltip placement="top">
                    <template slot="title">
                      <span>修改</span>
                    </template>
                    <span size="small" type="link" @click="handleEdit(record)"
                      style="cursor:pointer;color:#1890FF">修改</span>
                  </a-tooltip>
                  <!-- <a-popconfirm title="确定删除?" okText="确定" cancelText="取消" @confirm="handleDelete(record)">
                <a-button type="primary" shape="circle" icon="delete"></a-button>
                  </a-popconfirm>-->
                </template>
              </span>
            </a-table>
          </div>
        </a-spin>
        <!-- <a-pagination size="small" showQuickJumper :defaultCurrent="2" :total="500" @change="onChange" /> -->
      </a-col>
    </a-row>

    <a-modal :title="title" :visible="visible" :centered="true" @cancel="handleCancel" :footer="null">
      <div class="waterArea" style="background-color:#fff">
        <a-spin :spinning="loading">
          <a-form :form="form">
            <a-form-item v-bind="formItemLayout" label="角色名称">
              <a-input v-decorator="['RoleName', { rules: [{ required: true, message: '请填写角色名称!' }] }]" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="是否部门权限">
              <a-switch v-decorator="['isDepartmentRole']" @change="onChangeSwitch" :checked="form.getFieldValue('isDepartmentRole')"/>
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="序号">
              <a-input v-decorator="['Sortnum']" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="备注">
              <a-input v-decorator="['Remark']" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout1" style="text-align:center;margin-bottom:0">
              <a-button type="primary" @click="ok">确定</a-button>
            </a-form-item>
          </a-form>
        </a-spin>
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import { getRoleInfo, getRoleList, saveRole, delRole, delRoles } from '@/api/role'
import { getMenuButtonsByRoleID, saveMenuButtons } from '@/api/permission'
import { getMenuList } from '@/api/menu'
import moment from 'moment'
import { authDevice } from '@/utils/mixin'
export default {
  mixins: [authDevice],
  data() {
    return {
      action: 'add',
      title: '',
      titlePer: '',
      tableCardLoad: false,
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      // checkedKeys: {
      //   checked: [],
      //   halfChecked: []
      // },
      checkedKeysAndHalf: {},
      selectedMenuKeys: [],
      treeData: [],
      replaceFields: {
        key: 'id',
        title: 'name'
      },
      spinning: false,
      data: [],
      queryParam: {},
      pagination: {
        onChange: (index, pageSize) => {
          this.pageOnChange(index, pageSize)
        },
        current: 1,
        total: 0,
        showQuickJumper: true,
        size: 'small',
        defaultPageSize: 10,
        showTotal: total => `共 ${total} 条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],
        onShowSizeChange: (index, pageSize) => {
          this.pageOnChange(index, pageSize)
        },
        position: 'top'
      },
      // 表头
      columns: [
        {
          title: '角色名称',
          dataIndex: 'RoleName',
          key: 'RoleName',
          align: 'center'
        },
        {
          title: '序号',
          dataIndex: 'Sortnum',
          key: 'Sortnum',
          align: 'center'
        },
        {
          title: '备注',
          dataIndex: 'Remark',
          key: 'Remark',
          align: 'center'
        },
        {
          title: '操作',
          width: '150px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      selectedRowKeys: [],
      visible: false,
      visiblePer: false,
      loading: false,
      loadingPer: false,
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 }
        }
      },
      formItemLayout1: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 0 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        }
      },
      currentId: null,
      selectedRoleId: null
    }
  },
  created() {
    var _this = this
    _this.spinning = true
    _this.initData(_this.queryParam)

    getMenuList().then(res => {
      this.treeData = JSON.parse(res)
    })
  },
  methods: {
    onCheck(checkedKeys, info) {
      // console.log(this.checkedKeys)
      // console.log('onCheck', checkedKeys, info);

      // var obj={
      //   MenuID:null,
      //   IsHalfChecked:null
      // }
      this.checkedKeysAndHalf.checked = checkedKeys
      this.checkedKeysAndHalf.halfChecked = info.halfCheckedKeys
    },
    ok() {
      const {
        form: { validateFields }
      } = this
      validateFields((errors, values) => {
        if (!errors) {
          this.loading = true
          setTimeout(() => {
            const value = {
              ...values,
              ID: this.currentId
            }
            saveRole(value).then(res => {
              this.currentId = null
              this.initData(this.queryParam)
              this.loading = false
              this.visible = false
            })
          }, 1000)
        } else {
        }
      })
    },
    initData(data) {
      var _this = this
      getRoleList(data)
        .then(res => {
          // if (res.success) {
          _this.data = res
          // _this.pagination.total = res.page.RecordCount
          // } else {
          //   this.$message.error(res.message)
          // }
        })
        .finally(() => {
          this.spinning = false
        })
    },
    handleCancel() {
      this.visible = false
    },
    handleCancelPer() {
      this.visiblePer = false
    },
    search(data) {
      var _this = this
      _this.spinning = true
      Object.assign(_this.queryParam, data)
      // _this.queryParam = Object.assign({}, data)
      _this.initData(_this.queryParam)
    },
    add() {
      this.title = '添加角色'
      this.action = 'add'
      this.visible = true
      this.form.resetFields()
    },

    pageOnChange(index, pageSize) {
      this.tableCardLoad = true
      Object.assign(this.pagination, {
        current: index,
        pageSize,
        index
      })
      Object.assign(this.queryParam, {
        pageSize,
        index
      })
      this.initData(this.queryParam)
    },
    onSelect(selectedKeys, e) {
      // this.ParentId = e.selectedNodes[0].data.props.name
      // this.form.setFieldsValue({ ParentName: this.ParentName })
      console.log(e.selectedNodes)
      this.selectedMenuKeys = selectedKeys
      console.log(this.selectedMenuKeys)
    },
    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    handleEdit(data) {
      this.spinning = true
      this.action = 'edit'
      this.title = '修改角色'
      getRoleInfo({ id: data.ID })
        .then(res => {
          this.visible = true
          this.loading = true
          setTimeout(() => {
            this.currentId = res.ID
            this.form.setFieldsValue({ Remark: res.Remark })
            this.form.setFieldsValue({ isDepartmentRole: res.isDepartmentRole })
            this.form.setFieldsValue({ RoleName: res.RoleName })
            this.form.setFieldsValue({ Sortnum: res.Sortnum })
          }, 500)
        })
        .finally(() => {
          this.loading = false
          this.spinning = false
        })
    },
    savePer() {
      console.log(this.checkedKeysAndHalf)
      var obj = {
        RoleId: this.selectedRoleId,
        // MenuIDs: this.checkedKeys.checked
        MenuIDs: this.checkedKeysAndHalf.checked,
        HalfMenuIDs: this.checkedKeysAndHalf.halfChecked
      }
      saveMenuButtons(obj).then(res => {
        if (res) {
          this.$message.success('保存成功')
        } else {
          this.$message.error('保存失败')
        }
      })
    },
    view(data) { },
    del() {
      this.spinning = true
      delRoles(this.selectedRowKeys).then(res => {
        this.initData(this.queryParam)
        this.selectedRowKeys = []
      })
    },
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    setRow(record) {
      return {
        on: {
          // 事件
          click: event => {
            this.loadingPer = true
            this.selectedRoleId = record.ID
            getMenuButtonsByRoleID({ roleId: record.ID })
              .then(res => {
                // this.treeData.forEach(a=>{
                //   if(a.)
                // })
                // Object.assign(this.checkedKeys, {
                //   checked: res.MenuIDs.map(a => {
                //     return parseString(a)
                //   }),
                //   // halfChecked: res.HalfMenuIDs.map(a => {
                //   //   return parseString(a)
                //   // })
                // })
                this.checkedKeys = res.MenuIDs.map(a => {
                  return String(a)
                })
                this.checkedKeysAndHalf.checked = res.MenuIDs
                this.checkedKeysAndHalf.halfChecked = res.HalfMenuIDs
                // this.checkedKeys.halfChecked = res.HalfMenuIDs.map(a => {
                //   return parseString(a)
                // })
                // console.log(this.checkedKeys)
              })
              .finally(() => {
                this.loadingPer = false
              })
          }
        }
      }
    },
    setRowClassName(record, idx) {
      return record.ID === this.selectedRoleId ? 'bg-row' : ''
    },
    onChangeSwitch(isChecked) {
    }
  }
}
</script>
<style lang="less">

</style>
<style lang="less" scoped>
.actionButton {
  margin-left: 10px;
}
</style>
